/**
 *    TimedProfiles - let Android perform tasks based on conditions
 *    Copyright (C) 2011  Daniel Weinhold
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * */
package de.drak.Profiles.plugins;

import de.drak.Profiles.OnlineHelp;
import de.drak.Profiles.R;
import de.drak.Profiles.TimedProfiles;
import android.app.Activity;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;

/**Select a Ringtone for the Change-Ringtone-Setting*/
public class ToneSetter extends Activity {
	private final int Set_Ringtone = 456;
	private  final int Set_Notify = 457;
	private static final int MENU_SAVE = 1;
	private static final int MENU_DONT_SAVE = 2;
	/**Ringtone*/
	static final String SAVE_RING = "tone.ring";
	/**Notification Sound*/
	static final String SAVE_NOTI = "tone.noti";

	private boolean isCancelled;
	private String[] ToneURI;
	private CheckBox[] on_off_button;
	@Override
	public void onCreate(final Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.set_tone);
		TimedProfiles.createTitle(this, getString(R.string.plugin_toneseter));
		
		ToneURI = new String[2];
		on_off_button = new CheckBox[]
		                            {(CheckBox)findViewById(R.id.CheckBox01),
									 (CheckBox)findViewById(R.id.CheckBox02)};
		
		Button pickR = (Button) findViewById(R.id.Button01);
		pickR.setOnClickListener(picker);

		Button pickN = (Button) findViewById(R.id.Button02);
		pickN.setOnClickListener(picker);
		/*
		 * if savedInstanceState == null, then we are entering the Activity directly and we need to check whether the
		 * Intent has forwarded a Bundle extra (e.g. whether we editing an old condition or creating a new one)
		 */
		if (savedInstanceState == null)
		{
			final Bundle forwardedBundle = getIntent().getBundleExtra(QueryReceiver.INTENT_BUNDLE);

			/*
			 * the forwardedBundle would be null if this was a new condition
			 */
			if (forwardedBundle == null)
			{
				//current tone
				SaveTone(RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE), RingtoneManager.TYPE_RINGTONE);
				SaveTone(RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION), RingtoneManager.TYPE_NOTIFICATION);
				
				((CheckBox) findViewById(R.id.CheckBox03)).setChecked(true);
				((CheckBox) findViewById(R.id.CheckBox03)).setVisibility(View.VISIBLE);
			}else{
				if(getIntent().hasExtra(TimedProfiles.INTENT_BUNDLE_UNSET))
				{
					//there is an unset bundle
					((CheckBox) findViewById(R.id.CheckBox03)).setVisibility(View.VISIBLE);
					((CheckBox) findViewById(R.id.CheckBox03)).setText(R.string.unsetbundle_edit);
				}
				
				if(forwardedBundle.containsKey(ToneSetter.SAVE_RING))
				{
					String uri = forwardedBundle.getString(ToneSetter.SAVE_RING);
					
					SaveTone(uri.equals("Silent")?null:Uri.parse(uri), RingtoneManager.TYPE_RINGTONE);
					
					((CheckBox)findViewById(R.id.CheckBox01)).setChecked(true);
				}
				if(forwardedBundle.containsKey(ToneSetter.SAVE_NOTI))
				{
					String uri = forwardedBundle.getString(ToneSetter.SAVE_NOTI);
					
					SaveTone(uri.equals("Silent")?null:Uri.parse(uri), RingtoneManager.TYPE_NOTIFICATION);
					
					((CheckBox)findViewById(R.id.CheckBox02)).setChecked(true);
				}
			}
		}
	}
	
	private View.OnClickListener picker = new View.OnClickListener(){
		@Override
		public void onClick(View v) {
			final int arr_ind = v.getId()==R.id.Button01?0:1;
			String uri = null;
			
			if(ToneURI[arr_ind] != null)
				if(!ToneURI[arr_ind].equals("Silent"))
				{
					uri = ToneURI[arr_ind];
				}
			
			on_off_button[arr_ind].setChecked(true);
			
			Intent intent = new Intent( RingtoneManager.ACTION_RINGTONE_PICKER);
			intent.putExtra( RingtoneManager.EXTRA_RINGTONE_TYPE, v.getId()==R.id.Button01?
																	RingtoneManager.TYPE_RINGTONE:
																	RingtoneManager.TYPE_NOTIFICATION);
			intent.putExtra( RingtoneManager.EXTRA_RINGTONE_TITLE, getString(v.getId()==R.id.Button01?
																	R.string.plugin_vol_ring:
																	R.string.plugin_vol_info));
			
			if( uri != null)
			{
				intent.putExtra( RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, Uri.parse( uri));
			}
			else
			{
				intent.putExtra( RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri)null);
			}
			startActivityForResult( intent, v.getId()==R.id.Button01?Set_Ringtone:Set_Notify);
		}
	};
	
	private void SaveTone(Uri ur, int type)
	{
		Button but;
		if((type-=RingtoneManager.TYPE_RINGTONE)==1)//type - ring == 1 => NOTIFY
		{
			but = (Button) findViewById(R.id.Button02);
		}else{
			but = (Button) findViewById(R.id.Button01);
		}
		if (ur != null) {
			ToneURI[type] = ur.toString();
			Ringtone r = RingtoneManager.getRingtone(this, ur);
			but.setText(r.getTitle(this));
		}else{
			ToneURI[type] = "Silent";
			but.setText("Silent");
		}
	}
	
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
            Intent data) {
    	if(requestCode == Set_Ringtone || requestCode == Set_Notify){
	    	if (resultCode == RESULT_OK) {
    			SaveTone((Uri) data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI),
    												requestCode == Set_Notify?RingtoneManager.TYPE_NOTIFICATION:RingtoneManager.TYPE_RINGTONE);
    		}
    	}
    }
    
	@Override
	public void finish()
	{
		if (isCancelled)
			setResult(RESULT_CANCELED);
		else
		{
			if(!on_off_button[0].isChecked()
					&&!on_off_button[1].isChecked())
			{
				setResult(TimedProfiles.RESULT_REMOVE);
				super.finish();
				return;
			}

			
			/*
			 * This is the return Intent, into which we'll put all the required extras
			 */
			final Intent returnIntent = new Intent();

			/*
			 * This extra is the data to ourselves: either for the Activity or the BroadcastReceiver. Note that anything placed in
			 * this Bundle must be available to Locale's class loader. So storing String, int, and other basic objects will work
			 * just fine. You cannot store an object that only exists in your app, as Locale will be unable to serialize it.
			 */
			final Bundle storeAndForwardExtras = new Bundle();
			
			if(on_off_button[0].isChecked())
			{
				storeAndForwardExtras.putString(ToneSetter.SAVE_RING, ToneURI[0]);
			}

			if(on_off_button[1].isChecked())
			{
				storeAndForwardExtras.putString(ToneSetter.SAVE_NOTI, ToneURI[1]);
			}
			
			storeAndForwardExtras.putInt(QueryReceiver.TYPE_FIELD, QueryReceiver.IS_TONE);
			
			returnIntent.putExtra(TimedProfiles.INTENT_INFO_STR,
					String.format("R %s, N %s",
							on_off_button[0].isChecked()?((Button) findViewById(R.id.Button01)).getText():"-",
							on_off_button[1].isChecked()?((Button) findViewById(R.id.Button02)).getText():"-"
							));
			returnIntent.putExtra(QueryReceiver.INTENT_BUNDLE, storeAndForwardExtras);

			if(((CheckBox) findViewById(R.id.CheckBox03)).getVisibility()==View.VISIBLE
					&& ((CheckBox) findViewById(R.id.CheckBox03)).isChecked())
			{
				//new instance - unset bundle
				final Bundle endB = new Bundle(),
							caps  = new Bundle();
				
				if(on_off_button[0].isChecked())
				{
					SaveTone(RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE), RingtoneManager.TYPE_RINGTONE);
					endB.putString(ToneSetter.SAVE_RING, ToneURI[0]);
				}
				if(on_off_button[1].isChecked())
				{
					SaveTone(RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION), RingtoneManager.TYPE_NOTIFICATION);
					endB.putString(ToneSetter.SAVE_NOTI, ToneURI[1]);
				}
				
				caps.putString(TimedProfiles.INTENT_INFO_STR,
						String.format("R %s, N %s",
								on_off_button[0].isChecked()?((Button) findViewById(R.id.Button01)).getText():"-",
								on_off_button[1].isChecked()?((Button) findViewById(R.id.Button02)).getText():"-"
								));
				endB.putInt(QueryReceiver.TYPE_FIELD, QueryReceiver.IS_TONE);
				
				caps.putBundle(QueryReceiver.INTENT_BUNDLE, endB);
				
				returnIntent.putExtra(TimedProfiles.INTENT_BUNDLE_UNSET, caps);
			}//unset
			
			setResult(RESULT_OK, returnIntent);
		}

		super.finish();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean onCreateOptionsMenu(final Menu menu)
	{
		super.onCreateOptionsMenu(menu);

		final Intent helpIntent = new Intent(this, OnlineHelp.class);
		helpIntent.putExtra("com.twofortyfouram.locale.intent.extra.HELP_URL", OnlineHelp.HELP_URL_PRE+"plugin/ToneSeter");

		// Note: title set in onCreate
		helpIntent.putExtra(TimedProfiles.INTENT_TITLE, getTitle());

		menu.add(R.string.onlinehelp)
			.setIcon(android.R.drawable.ic_menu_help).setIntent(helpIntent);
		menu.add(0, MENU_DONT_SAVE, 0, android.R.string.cancel)
			.setIcon(android.R.drawable.ic_menu_close_clear_cancel).getItemId();
		menu.add(0, MENU_SAVE, 0, R.string.plugin_save)
			.setIcon(android.R.drawable.ic_menu_save).getItemId();
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean onMenuItemSelected(final int featureId, final MenuItem item)
	{
		switch (item.getItemId())
		{
			case MENU_SAVE:
			{
				finish();
				return true;
			}
			case MENU_DONT_SAVE:
			{
				isCancelled = true;
				finish();
				return true;
			}
		}

		return super.onOptionsItemSelected(item);
	}
}
